import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbcurriculum, tbgroup, tbmajor } from '../../../../atoms/db';


const logger = anylogger('pages/api/basicinformation/curriculum/query.api');

export type IData = ITbcurriculum & ITbgroup & ITbmajor;

export type Result = {
	count: number;
	data: IData[];
};

export type Query = {
	/**
	 * 查询内容
	 */
	q: string;
	/**
	 * 页码
	 */
	page: string;
	/**
	 * 页数
	 */
	pagesize: string;
}

/**
 * 专业管理-列表查询
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg query:', req.query);
		//解析查询条件
		const { q, ...rest } = req.query as Query;
		const page = Number(rest.page || '1');
		const pagesize = Number(rest.pagesize || '10');

		//获取数据
		//页数
		const d1 = SetCon(q);
		const allData = await d1.select('curriculum_id');
		//分页
		const offset = (page - 1) * pagesize;
		const d2 = SetCon(q);
		const dtTable = await d2.select('*')
			.orderBy('curriculum_id')
			.limit(pagesize)
			.offset(offset);
		//返回数据
		const datagroup = await tbgroup().select('*');
		const datamajor = await tbmajor().select('*');
		const mapgroup = datagroup.reduce((pre, cur) => {
			return pre.set(cur.group_id, cur.groupname);
		}, new Map<string, string>());
		const mapmajor = datamajor.reduce((pre, cur) => {
			return pre.set(cur.major_id, cur.majorname);
		}, new Map<string, string>());
		const r = dtTable.map((it) => {
			const groupname = mapgroup.get(it.group_id);
			const majorname = mapmajor.get(it.major_id);
			return {
				...it,
				groupname,
				majorname
			} as IData;
		});
		res.status(200).json({
			count: allData.length,
			data: r
		});
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({
			count: 0,
			data: []
		});
	}
});

export const config = {} as PageConfig;

export default handler;

/**
 * 设置取数条件
 * @param q 
 * @returns 
 */
function SetCon(q: string) {
	const d = tbcurriculum();
	if (q) {
		const q1 = q.trim();
		d.where('curriculum_id', 'like', `%${q1}%`)
			.orWhere('coursename', 'like', `%${q1}%`);
		// .orWhere('majorname', 'like', `%${q1}%`)
		// 	.orWhere('groupname', 'like', `%${q1}%`)
	}
	return d;
}
